//
//  LogisticsHallViewController.m
//  Logistics
//
//  Created by 华谕 on 2017/10/30.
//  Copyright © 2017年 HUYU. All rights reserved.
//

#import "LogisticsHallViewController.h"
#import "NearLogisModel.h"
#import "CloseGoodsAddressViewController.h"
#import "TruckTypeViewController.h"
#import "CompanyHomeViewController.h"
#import "ScreeningServicesViewController.h"
#import "LogisticsLocationViewController.h"
#import "LogisticsMapViewController.h"

static NSString *cellPath = @"nearAddressCell";
@interface LogisticsHallViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    UIView *screeView;
    UILabel *startLab;
    UIView *showView;
}
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, strong)NSMutableArray *allLineAry;
@property (nonatomic, assign)NSInteger page;
@property (nonatomic, strong)NSString *serveId;
@property (nonatomic, strong)NSString *serveName;
@property (nonatomic, strong)NSString *latitude;
@property (nonatomic, strong)NSString *lontude;
@property (nonatomic, strong)NearLogisModel *Phonemodel;
@property (nonatomic, strong)NSString *CallPhone;
@property (nonatomic, assign)BOOL isCreat;

@end

@implementation LogisticsHallViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(callPhonesNotifice:) name:@"callPhones" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"callPhones" object:nil];
}


- (void)callPhonesNotifice:(NSNotification *)center
{
    NSString *timeStr = [center object];
    Student *stu = [Student studentWith:_Phonemodel.company.logo name:_Phonemodel.company.nameShort Phone:_CallPhone Times:timeStr];
    BOOL isInsert = [StudentFMDNManager addStudent:stu];
    
    if (isInsert) {
        NSLog(@"插入成功");
    } else {
        NSLog(@"插入失败");
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    _isCreat = YES;
    self.navigationItem.title = @"附近物流";
    self.view.backgroundColor = BacksColor;
    self.navigationController.navigationBar.translucent = NO;
    if (_serveId == nil)
    {
        _serveId = @"";
        _serveName = @"全部服务";
    }
    _page = 0;
    _allLineAry = [NSMutableArray arrayWithCapacity:0];
    if ([[LTools cacheForKey:SERVER_latitude] isEqualToString:@""])
    {
        [LTools showMBProgressWithText:@"定位失败" addToView:self.view];
        return;
    }
    _latitude = [LTools cacheForKey:SERVER_latitude];
    _lontude = [LTools cacheForKey:SERVER_longitude];
    [self creatUI];
    [self requestNearLogistics];
}

- (void)reloadServices:(NSString *)name ServeId:(NSString *)serveId
{
    if (!_isCreat)
    {
        _serveId = serveId;
        _serveName = name;
    }
    else
    {
        if ([[LTools cacheForKey:SERVER_latitude] isEqualToString:@""])
        {
            [LTools showMBProgressWithText:@"定位失败" addToView:self.view];
            return;
        }
        _latitude = [LTools cacheForKey:SERVER_latitude];
        _lontude = [LTools cacheForKey:SERVER_longitude];
        _serveId = serveId;
        _serveName = name;
        startLab.text = name;
        _page = 0;
        [self requestNearLogistics];
    }
}


- (void)creatUI
{
    
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 45*displaywidth, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT-TABBAR_HEIGHT-45*displaywidth) style:UITableViewStylePlain];
    _tableview.backgroundColor = BacksColor;
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableview];
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewHeaderData)];
    self.tableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreFootData)];
    self.tableview.mj_footer.automaticallyHidden = YES;
    self.tableview.estimatedRowHeight = 0;
    self.tableview.estimatedSectionHeaderHeight = 0;
    self.tableview.estimatedSectionFooterHeight = 0;
    showView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    showView.backgroundColor = RGBA(0, 0, 0, 0.6);
    showView.hidden = YES;
    [sharedDelegate.window addSubview:showView];
    screeView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 45*displaywidth)];
    screeView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:screeView];
    [self creatScreeView];
    screeView.layer.shadowOpacity = 1;// 阴影透明度
    screeView.layer.shadowColor = RGB(187, 187, 187).CGColor;// 阴影的颜色
    screeView.layer.shadowOffset = CGSizeMake(1, 3);// 阴影的范围
    
}

- (void)loadNewHeaderData
{
    _page = 0;
    [self requestNearLogistics];
    
}

- (void)loadMoreFootData
{
    _page ++;
    [self requestNearLogistics];
    
}

- (void)creatScreeView
{
    NSArray *typeAry = @[_serveName,@"重拾定位",@"查看地图"];
    CGFloat W = SCREEN_WIDTH/typeAry.count;
    for (int i = 0; i < typeAry.count; i++)
    {
        UILabel *nameLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth+W*i, 0, W-40*displaywidth, 45*displaywidth) Font:15.0 Text:typeAry[i] Color:RGB(53, 53, 53)];
        [screeView addSubview:nameLab];
        UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(W-25*displaywidth+W*i, 17.5*displaywidth, 10*displaywidth, 10*displaywidth) ImageName:@"arrowicon"];
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        [screeView addSubview:imgView];
        UIButton *btn = [ZCControl createButtonWithFrame:CGRectMake(W*i, 0, W, 45*displaywidth) ImageName:nil Target:self Action:@selector(closeRoursAction:) Title:nil Font:12.0];
        btn.backgroundColor = [UIColor clearColor];
        btn.tag = 100+i;
        [screeView addSubview:btn];
        if (i == 0)
        {
            startLab = nameLab;
        }
        if (i != 0)
        {
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(W*i, 12.5*displaywidth, 1, 20*displaywidth)];
            lineView.backgroundColor = RGB(235, 235, 235);
            [screeView addSubview:lineView];
        }
        
    }
}

- (void)closeRoursAction:(UIButton *)btn
{
    NSInteger index = btn.tag-100;
    WEAKSELF;
    if (index == 0)
    {
        //选择服务
        ScreeningServicesViewController *vc = [[ScreeningServicesViewController alloc] init];
        vc.nameStr = _serveName;
        vc.closeBlock = ^(NSString *name, NSString *idstr)
        {
            weakSelf.serveName = name;
            startLab.text = name;
            weakSelf.serveId = idstr;
            [weakSelf loadNewHeaderData];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (index == 1)
    {
        //重拾定位
        LogisticsLocationViewController *locationVC = [[LogisticsLocationViewController alloc] init];
        locationVC.locationBlock = ^(NSString *lat, NSString *lng, NSString *address) {
            _latitude = lat;
            _lontude = lng;
            [weakSelf loadNewHeaderData];
        };
        [self.navigationController pushViewController:locationVC animated:YES];
    }
    else
    {
        //查看地图
        LogisticsMapViewController *mapVC = [[LogisticsMapViewController alloc] init];
//        mapVC.mapBlock = ^(NSString *companyId) {
//            
//        };
        [self.navigationController pushViewController:mapVC animated:YES];
        
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _allLineAry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor whiteColor];
    if (_allLineAry.count > 0)
    {
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10*displaywidth)];
        lineView.backgroundColor = BacksColor;
        [cell.contentView addSubview:lineView];
        NearLogisModel *model = _allLineAry[indexPath.row];
        UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth, 20*displaywidth, 105*displaywidth, 70*displaywidth) ImageName:@"newsImage"];
        if (model.company.logo.length > 0)
        {
            [imgView sd_setImageWithURL:[NSURL URLWithString:model.company.logo] placeholderImage:[UIImage imageNamed:@"newsImage"]];
        }
        imgView.contentMode = UIViewContentModeScaleAspectFill;
        imgView.layer.masksToBounds = YES;
        [cell.contentView addSubview:imgView];
        UIImageView *typeImgView = [ZCControl createImageViewWithFrame:CGRectMake(12*displaywidth, 17*displaywidth, 40*displaywidth, 40*displaywidth) ImageName:@"zx_icon01"];
        typeImgView.contentMode = UIViewContentModeScaleAspectFit;
        [cell.contentView addSubview:typeImgView];
        UILabel *typeLabel = [ZCControl createLabelWithFrame:CGRectMake(0, 2, 40*displaywidth, 20*displaywidth) Font:8.0 Text:model.company.serveName Color:[UIColor whiteColor]];
        typeLabel.transform =CGAffineTransformMakeRotation(-45*M_PI/180);
        [typeImgView addSubview:typeLabel];
        UILabel *comNameLab = [ZCControl createLabelWithFrame:CGRectMake(130*displaywidth, 20*displaywidth, 100*displaywidth, 25*displaywidth) Font:16.0 Text:model.company.nameShort Color:[UIColor blackColor]];
        comNameLab.textAlignment = NSTextAlignmentLeft;
        [cell.contentView addSubview:comNameLab];
        CGRect bounds = [comNameLab.text boundingRectWithSize:CGSizeMake(500*displaywidth, 25*displaywidth) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:NormalFontWithSize(15.0+fontScale) forKey:NSFontAttributeName] context:nil];
        CGFloat widrh = bounds.size.width+10*displaywidth;
        if (widrh > SCREEN_WIDTH-235*displaywidth)
        {
            widrh = SCREEN_WIDTH-235*displaywidth;
        }
        comNameLab.frame = CGRectMake(130*displaywidth, 20*displaywidth, widrh, 25*displaywidth);
        widrh+=135*displaywidth;
        if ([model.company.shi integerValue] == 1)
        {
            UILabel *shiLab = [ZCControl createLabelWithFrame:CGRectMake(widrh, 25*displaywidth, 15*displaywidth, 15*displaywidth) Font:10.0 Text:@"实" Color:[UIColor whiteColor]];
            shiLab.textAlignment = NSTextAlignmentCenter;
            shiLab.backgroundColor = RGB(204, 153, 102);
            [cell.contentView addSubview:shiLab];
            widrh+=20*displaywidth;
        }
        if ([model.company.bao integerValue] == 1)
        {
            UILabel *baoLab = [ZCControl createLabelWithFrame:CGRectMake(widrh, 25*displaywidth, 15*displaywidth, 15*displaywidth) Font:10.0 Text:@"保" Color:[UIColor whiteColor]];
            baoLab.textAlignment = NSTextAlignmentCenter;
            baoLab.backgroundColor = RGB(0, 153, 255);
            [cell.contentView addSubview:baoLab];
        }
        UILabel *sketchLab = [ZCControl createLabelWithFrame:CGRectMake(130*displaywidth, 50*displaywidth, SCREEN_WIDTH-180*displaywidth, 20*displaywidth) Font:11.0 Text:model.company.sketch Color:BlaTitColor];
        [cell.contentView addSubview:sketchLab];
        UIButton *callBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-45*displaywidth, 20*displaywidth, 30*displaywidth, 30*displaywidth) ImageName:@"bigtel" Target:self Action:@selector(callPhoneAction:) Title:nil Font:12.0];
        callBtn.tag = indexPath.row + 3000;
        [cell.contentView addSubview:callBtn];
        UILabel *addressLab = [ZCControl createLabelWithFrame:CGRectMake(130*displaywidth, 70*displaywidth, SCREEN_WIDTH-200*displaywidth, 25*displaywidth) Font:10.0 Text:model.address Color:RGB(154, 154, 154)];
        addressLab.textAlignment = NSTextAlignmentLeft;
        [cell.contentView addSubview:addressLab];
        CGFloat distance = [model.distance floatValue]/1000.0;
        NSString *string = [NSString stringWithFormat:@"%.1lfkm",distance];
        if (distance == 0)
        {
            string = @"0km";
        }
        UILabel *distanceLab = [ZCControl createLabelWithFrame:CGRectMake(SCREEN_WIDTH-70*displaywidth, 70*displaywidth, 70*displaywidth, 20*displaywidth) Font:10.0 Text:string Color:RGB(154, 154, 154)];
        distanceLab.textAlignment = NSTextAlignmentCenter;
        [cell.contentView addSubview:distanceLab];
    }
    
    return cell;
}

- (void)callPhoneAction:(UIButton *)btn
{
    NSInteger index = btn.tag-3000;
    NearLogisModel *model = _allLineAry[index];
    showView.hidden = NO;
    [self creatShowView:model];

}

- (void)creatShowView:(NearLogisModel *)model
{
    for (id v in showView.subviews)
    {
        [v removeFromSuperview];
    }
    NSString *phone = model.phone;
    NSString *fixPhone = model.fixPhone;
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(40*displaywidth, SCREEN_HEIGHT/2-100*displaywidth, SCREEN_WIDTH-80*displaywidth, 185*displaywidth)];
    whiteView.backgroundColor = [UIColor whiteColor];
    whiteView.layer.cornerRadius = 10;
    whiteView.layer.masksToBounds = YES;
    [showView addSubview:whiteView];
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-80*displaywidth, 85*displaywidth)];
    topView.backgroundColor = ThemeColor;
    [whiteView addSubview:topView];
    UIButton *closeBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-120*displaywidth, 10*displaywidth, 25*displaywidth, 25*displaywidth) ImageName:@"closeicon" Target:self Action:@selector(closeViewAction) Title:nil Font:12.0];
    [topView addSubview:closeBtn];
    UILabel *tostLab = [ZCControl createLabelWithFrame:CGRectMake(0, 45*displaywidth, SCREEN_WIDTH-80*displaywidth, 30*displaywidth) Font:14.0 Text:@"联系时，请说明信息来自专线网" Color:RGB(218,222,232)];
    tostLab.textAlignment = NSTextAlignmentCenter;
    [topView addSubview:tostLab];
    CGFloat H = 85*displaywidth;
    if (phone.length > 0)
    {
        UIButton *btn = [ZCControl createButtonWithFrame:CGRectMake(0, H, SCREEN_WIDTH-80*displaywidth, 49*displaywidth) ImageName:nil Target:self Action:@selector(callphone:) Title:model.name Font:15.0];
        objc_setAssociatedObject(btn, "firstObject", model, OBJC_ASSOCIATION_RETAIN_NONATOMIC);   //实际上就是KVC
        objc_setAssociatedObject(btn, "secondObject", phone, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [btn setTitleColor:ThemeColor forState:UIControlStateNormal];
        [whiteView addSubview:btn];
        H = 135*displaywidth;
    }
    if (fixPhone.length > 0)
    {
        if (H == 135*displaywidth)
        {
            UIView *lineview = [[UIView alloc] initWithFrame:CGRectMake(10*displaywidth, H-1*displaywidth, SCREEN_WIDTH-100*displaywidth, 1*displaywidth)];
            lineview.backgroundColor = RGB(218, 222, 232);
            [whiteView addSubview:lineview];

        }
        UIButton *btn2 = [ZCControl createButtonWithFrame:CGRectMake(0, H, SCREEN_WIDTH-80*displaywidth, 50*displaywidth) ImageName:nil Target:self Action:@selector(callphone:) Title:@"售后服务" Font:15.0];
        objc_setAssociatedObject(btn2, "firstObject", model, OBJC_ASSOCIATION_RETAIN_NONATOMIC);   //实际上就是KVC
        objc_setAssociatedObject(btn2, "secondObject", fixPhone, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [btn2 setTitleColor:ThemeColor forState:UIControlStateNormal];
        [whiteView addSubview:btn2];
        H+=50*displaywidth;
    }
    whiteView.frame = CGRectMake(40*displaywidth, SCREEN_HEIGHT/2-100*displaywidth, SCREEN_WIDTH-80*displaywidth, H);
    
}

- (void)closeViewAction
{
    showView.hidden = YES;

}

- (void)callphone:(UIButton *)btn
{
    showView.hidden = YES;
    _Phonemodel = objc_getAssociatedObject(btn, "firstObject");
    NSString *phone = objc_getAssociatedObject(btn, "secondObject");
    _CallPhone = phone;
    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phone]]];

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NearLogisModel *model = _allLineAry[indexPath.row];
    CompanyHomeViewController *vc = [[CompanyHomeViewController alloc] init];
    vc.comPanyId = s_str(model.company.ID);
    [self.navigationController pushViewController:vc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100*displaywidth;
}

- (void)requestNearLogistics
{
    WEAKSELF;
    NSDictionary *dic = @{ @"lng":_lontude,
                           @"page":s_Integer(_page),
                           @"size":@"10",
                           @"serveId":_serveId,
                           @"lat":_latitude};
    [HYBaseHandler requestWithTheFormUrl:SERVER_NearLogis Parmers:dic Success:^(id obj) {
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        if ([obj server_Getcodecheck])
        {
            NSArray *lineAry = [NearLogisModel mj_objectArrayWithKeyValuesArray:obj[@"data"][@"content"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (_page == 0)
                {
                    [weakSelf.allLineAry removeAllObjects];
                }
                [weakSelf.allLineAry addObjectsFromArray:lineAry];
                [weakSelf.tableview reloadData];
            });
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
